#!/usr/bin/env python
# -*- coding: utf-8 -*-

import httplib, urllib, urllib2, re, os
httplib.HTTPConnection.debuglevel = 1
from sets import Set as set

""" 環境變數 """
defaultDIR = './downloads'


""" 以下不需更動 """
# 取得程式所在位置
programDIR = os.getcwd()
url = ''
newUrl = ''
theAlbum = ''
params = {}

def createDefaultDIR(defaultDIR):
    if (not os.path.isdir(defaultDIR)):
        os.mkdir(defaultDIR, 0700)

def getPage(url, params):
    data = urllib.urlencode(params)
    request = urllib2.Request(url, data)
    opener = urllib2.build_opener()
    request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; MyIE2; .NET CLR 1.1.4322)')
    data = opener.open(request).readlines()

    return data

def getLastPage(url, params):
    page = 0
    run = 'True'
    try:
        tmp = getPage(url, params)
    except httplib.BadStatusLine:
        tmp = getPage(url, params)

    if tmp != "": 
        #imgPage.append(tmp)
        for line in tmp:
            #print line
            if run == 'True':
                if re.search(r'title=\"Last', line):
                    pageN = line.split('=')
                    pageN = pageN[6]
                    pageN = pageN.split('"')[0]
                    page = int(pageN)
                    run == 'False'
    return page

def getLastBook(url, params):
    book = 0
    run = 'True'
    tmp = getPage(url, params)
    if tmp != "":
        for line in tmp:
            if run == 'True':
                if re.search(r'Albums', line):
                    bookN = line.split(' ')
                    #print bookN[2]
                    book = bookN[2]
                    run == 'False'
    return book

def getItemUrl(page, pattern, token, splitN):
    list = []
    for line in page:
        if re.search(pattern, line):
            tmp = []
            tmp = line.split(token)
            itemUrl = tmp[splitN].replace('./', 'http://www.wretch.cc/album/')
            itemUrl = itemUrl.replace('&amp;','&')                                                                  
            if itemUrl != 'small-e':
                list.append(itemUrl)
    return list

def getImgUrl(line, pattern, token, splitN):
    itemUrl = ''
    if re.search(pattern, line):
        tmp = []
        tmp = line.split(token)
        itemUrl = tmp[splitN].replace('&amp;','&')
    return itemUrl

def getImage(url, params, headers, info):
    tmp = url.split('/')
    fileName = tmp[len(tmp) - 1]
    checkit = programDIR + "/" + defaultDIR + "/" + info[0] + "/" + info[1] +  "/" + fileName
    #print os.path.isfile(checkit)
    if os.path.isfile(checkit):
        #print "Skip!!"
        pass
    else:
        data = urllib.urlencode(params)
        request = urllib2.Request(url, data)
        opener = urllib2.build_opener()
    
        for i in range(2):    
            request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; MyIE2; .NET CLR 1.1.4322)')
            request.add_header('Referer', url)
        picdata = opener.open(request).read()

        out = file(fileName, 'wb')
        out.write(picdata)
        out.close()

def checkPasswd(data):
    PASS = 'False'
    for line in data:
        test = re.search('protected', line)
        if test == None:
            # 密碼正確或不需密碼
            PASS = 'True'
        else:
            # 密碼錯誤
            PASS = 'False'
            break
    return PASS

def createDIR(defaultDIR, dir, subdir):
    if (not os.path.isdir(dir)):
        os.mkdir(dir, 0700)
    subdir = dir + "/" + subdir
    if (not os.path.isdir(subdir)):
        os.mkdir(subdir, 0700)

    return subdir

def getAlbumInfo(url):
    tmp = []
    tmp = url.split('=')
    tmpN = tmp[1].split('&')
    tmpB = tmp[2].split('&')
    info = []
    info.append(tmpN[0])
    info.append(tmpB[0])

    return info
        
def checkMode(url):
    global newUrl
    mode = '?'
    if re.search('(^[A-Za-z0-9-]+) ([0-9-]+$)', url):
        print "你輸入的是使用者帳號與相簿編號，啟動單本相簿下載模式"
        url = url.split(' ')
        newUrl = 'http://www.wretch.cc/album/album.php?id=' + url[0] + '&book=' + url[1]
        mode = 'S'

    elif re.search('(^[A-Za-z0-9-]+$)', url):
        print "你輸入的是使用者帳號，啟動多本相簿下載模式"
        #轉成網址
        newUrl = 'http://www.wretch.cc/album/' + url
        mode = 'M'

    elif re.search('(^http://www.wretch.cc/album/album.php\?id\=)([A-Za-z0-9-]+)\&book\=([A-Za-z0-9-]+$)', url):
        print "您輸入的是單本相簿，啟動單本下載模式"
        newUrl = url
        mode = 'S'

    elif re.match('(^http://www.wretch.cc/album/album.php\?id\=)([A-Za-z0-9-]+$)', url):
        print "你輸入的是整個使用者的相簿，啟動多本相簿下載模式"
        #修正網址
        tmp = url.split('=')
        tmp = tmp[1]
        newUrl = 'http://www.wretch.cc/album/' + tmp
        mode = 'M'

    elif re.search('(^http://www.wretch.cc/album/)([A-Za-z0-9-]+$)', url):
        print "你輸入的是整個使用者的相簿，啟動多本相簿下載模式"
        newUrl = url
        mode = 'M'
        
    return mode

def process (url, data):
    os.chdir(programDIR)
    params = {}
    pattern = './show.php'
    splitN = 1
    headers = ""
    last = 0
    PASSWDID = ''
    PASSWORD = ''
    flag = 'True'

    running = ''
    if checkPasswd(data) == 'False':
        running = 'True'
    else:
        running = 'False'

    while running == 'True':
        PASSWDID = 'passwd'
        #print global theAlbum
        PASSWORD = raw_input("需要密碼: ")
        if PASSWORD == '*':
            running = 'False'
            flag = 'False'
            break
        params = {PASSWDID:PASSWORD}

        data = getPage(url, params)
        
        if checkPasswd(data) == 'False':
            print "** 密碼錯誤 **"
            running = 'True'
        else:
            running = 'False'

    if flag == 'True':
        #print "Now", os.getcwd()
        list = getItemUrl(data, pattern, '"', 1)
        #print list
    
        info = []
        for link in list:
            info = getAlbumInfo(link)
            last = getLastPage(link, params)
            os.chdir(defaultDIR)
            #print "Now ", os.getcwd()
            path = createDIR(defaultDIR, info[0], info[1])
            os.chdir(path)
            #print path
            print "檔案將會下載到", os.getcwd()
            break
    
        n = last / 20 + 1
        print "# 總共有", n, "頁 #"
        i = 0
        for i in range(n):
            i = i + 1
            url =  url + '&page=' + str(i)

            data = getPage(url, params)
            list = getItemUrl(data, pattern, '"', splitN)

            imgPage = []
        
            print "下載第", i, "頁"

            for line in list:
                try:
                    data = getPage(line, params)
                except httplib.BadStatusLine:
                    data = getPage(line, params)
                imgPage.append(data)

            tmpLink = []
            for list in imgPage:
                test = getItemUrl(list, 'DisplayImage', '\'', 7)
                if test != "":
                    tmpLink.append(test)

            imgLink = []
            for i in tmpLink:
                try:
                    imgLink.append(i[0])
                except IndexError:
                    continue

            for link in imgLink:
                #print link
                theAlbum = link
                try:
                    getImage(link, params, headers, info)
                except urllib2.HTTPError:
                    pass
""" Main """
createDefaultDIR(defaultDIR)
if url == '':
    url = raw_input("請輸入網址: ")
MODE = checkMode(url)
url = newUrl
print url

""" 依輸入的網址抓取網頁 """
data = getPage(url, params)

if MODE == 'M':
    MirrorMode = 'True'
elif MODE == 'S':
    MirrorMode = 'False'
else:
    print "錯誤：未知的模式"

if MirrorMode == 'True':
    ulist = []
    book = getLastBook(url, params)
    bookN = int(book) / 20 + 1
    
    if bookN > 0:
        print '找到', book, '本相簿'
        tmp = url
        for b in range(bookN):
            #print b + 1
            url = tmp + '&page=' + str(b+1)
            #print url
            data = getPage(url, params)
            ulist = ulist + getItemUrl(data, 'album.php', '"', 1)
    
    ulist = list(set(ulist))
    
    c = 0
    for url in ulist:
        c = c + 1
        print "-" * 80
        print "[", c, "]", url
        try:
            data = getPage(url, params)
        except urllib2.HTTPError, urllib2.URLError:
            data = getPage(url, params)
        try:    
            process(url, data)
        except urllib2.HTTPError, urllib2.URLError:
            process(url, data)
        
else:
    try:
        process(url, data)
    except urllib2.HTTPError, urllib2.URLError:
        process(url, data) 

print "\n\n下載完成！ :D\n"
